﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace Neoit.Utils.AspNetCore.Extensions
{
    public static class HttpContextExtension
    {
        public static string RealIP(this HttpContext httpContent)
        {
            //若有反向代理，如nginx需设置：proxy_set_header X-Real-IP $remote_addr;
            var realIp = httpContent.Request.Headers["X-Real-IP"].ToString();
            //若有反向代理，如nginx需设置：proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            if (string.IsNullOrEmpty(realIp)) realIp = httpContent.Request.Headers["X-Forwarded-For"].ToString();
            if (string.IsNullOrEmpty(realIp)) realIp = httpContent.Connection.RemoteIpAddress.MapToIPv4().ToString();
            return realIp;
        }

        #region HasAttribute
        public static bool HasAttribute<TAttribute>(this ActionContext actionContext) where TAttribute : Attribute
        {
            if (actionContext.ActionDescriptor is ControllerActionDescriptor descriptor)
            {
                return HasAttribute<TAttribute>(descriptor);
            }
            return false;
        }

        public static bool HasAttribute<TAttribute>(this HttpContext httpContext) where TAttribute : Attribute
        {
            var endpoint = httpContext.GetEndpoint();
            if (endpoint != null)
            {
                var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
                return HasAttribute<TAttribute>(actionDescriptor);
            }
            return false;
        }

        private static bool HasAttribute<TAttribute>(ControllerActionDescriptor controllerAction)
        {
            if (controllerAction == null) return false;
            var hasAttribute = controllerAction.MethodInfo.GetCustomAttributes(typeof(TAttribute), true).Any();
            if (!hasAttribute) hasAttribute = controllerAction.ControllerTypeInfo.GetCustomAttributes(typeof(TAttribute), true).Any();
            return hasAttribute;
        }
        #endregion
    }
}
